package com.lijinjiang.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * 响应字节数据：设置字节数据的响应体
 */
@WebServlet("/demo04")
public class Demo04 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.获取输入流
        // 读取webapp目录下文件
        InputStream is = this.getServletContext().getResourceAsStream("static/images/a.png");
        // 2.获取 response 字节输出流
        ServletOutputStream os = response.getOutputStream();
        // 3.完成流的数据传输
        /*byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }*/
        // 使用common-io工具类实现流的传输
        IOUtils.copy(is, os);
        is.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
